<template>
  <div class="container">
    <!-- 顶部搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-wrapper">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item>
            <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable>
              <el-option
                v-for="item in projectOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryParams.customerId" placeholder="请选择客户" clearable>
              <el-option
                v-for="item in customerOptions"
                :key="item.id"
                :label="item.companyName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryParams.personId" placeholder="请选择业务员" clearable>
              <el-option
                v-for="item in personOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button :icon="Refresh" @click="resetQuery">
              重置
            </el-button>
            <el-button type="primary" :icon="Plus" @click="handleAdd">
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="dataList"
        :height="tableHeight"
        element-loading-text="加载中..."
        element-loading-background="rgba(255, 255, 255, 0.7)"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column type="index" width="60" label="序号" align="center" />
        <el-table-column prop="projectName" label="项目名称" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="customerName" label="客户名称" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="personName" label="业务员" min-width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="targetAmount" label="目标金额(元)" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="price-value">{{ formatPrice(scope.row.targetAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="grossMargin" label="毛利率(%)" min-width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPercent(scope.row.grossMargin) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row.id)">
              查看
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
            <el-button type="success" size="small" @click="handlePrint(scope.row)">
              生产预算单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 项目选择器对话框 -->
    <ArchiveSelector
      v-model="projectSelectorVisible"
      title="选择项目"
      :search-fields="projectSearchFields"
      :table-columns="projectTableColumns"
      :fetch-data-api="fetchProjectList"
      :multiple="false"
      @confirm="handleProjectSelect"
    />

    <!-- 打印预算单弹窗 -->
    <el-dialog
      v-model="budgetDialog.visible"
      :title="budgetDialog.title"
      :width="budgetDialog.width"
      :before-close="handleCloseBudgetDialog">
      <div class="budget-content" id="budgetContent">
        <div class="budget-header">
          <div class="budget-logo">
            <img src="@/assets/logo.png" alt="公司logo" class="logo-image">
          </div>
          <div class="budget-info">
            <h2>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspV9申请调价后项目投资预算表（含税）</h2>
          </div>
          <div class="budget-date">
            <div>日期：{{ new Date().toLocaleDateString() }}</div>
          </div>
        </div>
        
        <table class="budget-table">
          <tr>
            <td>集成规划类型：</td>
            <td colspan="1">{{ currentBudgetSheet.integratedPlanningType || '' }}</td>
            <td colspan="6"></td>
          </tr>
          <tr>
            <td>销售订单类型</td>
            <td colspan="1">{{ currentBudgetSheet.saleType || '' }}</td>
            <td>业务员：</td>
            <td colspan="2">{{ currentBudgetSheet.personName || '' }}</td>
            <td>销售预算金额</td>
            <td>销售金额</td>
            <td>毛利</td>

          </tr>
          
          <tr>
            <td>客户名称：</td>
            <td>{{ currentBudgetSheet.customerName || '' }}</td>
            <td>项目名称：</td>
            <td colspan="2">{{ currentBudgetSheet.projectName || '' }}</td>
            <td>{{ currentBudgetSheet.total ? currentBudgetSheet.total.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.targetAmount ? currentBudgetSheet.targetAmount.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.grossMargin ? currentBudgetSheet.grossMargin.toFixed(2) : '0.00' }}</td>
          </tr>
          
          <tr>
            <td>品项：</td>
            <td>预算金额（含税）</td>
            <td>销售金额（含税）</td>
            <td colspan="3">项目类别及备注下拉选择</td>
            <td colspan="2">附各项明细</td>
          </tr>

          <tr>
            <td>产品成本费用：</td>
            <td>{{ currentBudgetSheet.productCostExpenses ? currentBudgetSheet.productCostExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.productCostExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.productCostExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2">90</td>
          </tr>
          
          <tr>
            <td>产品包装费用：</td>
            <td>{{ currentBudgetSheet.productPackagingExpenses ? currentBudgetSheet.productPackagingExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.productPackagingExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.productPackagingExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3">国内项目</td>
            <td colspan="2">从产品费用中分离出来（外贸或特殊订单需求）</td>
          </tr>
          
          <tr>
            <td>产品运输费用：</td>
            <td>{{ currentBudgetSheet.productTransportExpenses ? currentBudgetSheet.productTransportExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.productTransportExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.productTransportExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2"></td>
          </tr>
          
          <tr>
            <td>货架安装费用：</td>
            <td>{{ currentBudgetSheet.shelfInstallationExpenses ? currentBudgetSheet.shelfInstallationExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.shelfInstallationExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.shelfInstallationExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2">附结构件明细表</td>
          </tr>
          
          <tr>
            <td>设备安装费用：</td>
            <td>{{ currentBudgetSheet.equipmentInstallationExpenses ? currentBudgetSheet.equipmentInstallationExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.equipmentInstallationExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.equipmentInstallationExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2">附汇总清单</td>
          </tr>
          
          <tr>
            <td>电控安装费用：</td>
            <td>{{ currentBudgetSheet.electricControlInstallationExpenses ? currentBudgetSheet.electricControlInstallationExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.electricControlInstallationExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.electricControlInstallationExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2"></td>
          </tr>
          
          <tr>
            <td>电控调试费：</td>
            <td>{{ currentBudgetSheet.electricControlDebugExpenses ? currentBudgetSheet.electricControlDebugExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.electricControlDebugExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.electricControlDebugExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2"></td>
          </tr>
          
          <tr>
            <td>软件调试费：</td>
            <td>{{ currentBudgetSheet.softwareDebugExpenses ? currentBudgetSheet.softwareDebugExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.softwareDebugExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.softwareDebugExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2">含系统集成软件调试人员差旅+人工</td>
          </tr>
          
          <tr>
            <td>项目管理费：</td>
            <td>{{ currentBudgetSheet.projectManagementExpenses ? currentBudgetSheet.projectManagementExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.projectManagementExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.projectManagementExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3">常规性订单</td>
            <td colspan="2">项目现场人员驻场差旅+公关招待+提成+人工（原财务项目管理费用口径）</td>
          </tr>
          
          <tr>
            <td>运营管理费：</td>
            <td>{{ currentBudgetSheet.operationManagementExpenses ? currentBudgetSheet.operationManagementExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.operationManagementExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.operationManagementExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2">运营中心（除项目经理外）：费用及人工</td>
          </tr>
          
          <tr>
            <td>质保期(年限)：</td>
            <td>{{ currentBudgetSheet.warrantyPeriod ? currentBudgetSheet.warrantyPeriod : '0' }}</td>
            <td>{{ currentBudgetSheet.warrantyPeriod && currentBudgetSheet.grossMargin ? (currentBudgetSheet.warrantyPeriod * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3">一年不收费</td>
            <td colspan="2"></td>
          </tr>
          
          <tr>
            <td>其他费用：</td>
            <td>{{ currentBudgetSheet.otherExpenses ? currentBudgetSheet.otherExpenses.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.otherExpenses && currentBudgetSheet.grossMargin ? (currentBudgetSheet.otherExpenses * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3">非标颜色费</td>
            <td colspan="2"></td>
          </tr>
          
          <tr>
            <td>营销费用：</td>
            <td>{{ currentBudgetSheet.marketingExpensesPrice ? currentBudgetSheet.marketingExpensesPrice.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.marketingExpensesPrice && currentBudgetSheet.grossMargin ? (currentBudgetSheet.marketingExpensesPrice * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3">不提供发票</td>
            <td colspan="2"></td>
          </tr>
          
          <tr>
            <td>财务成本：</td>
            <td>{{ currentBudgetSheet.financialCost ? currentBudgetSheet.financialCost.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.financialCost && currentBudgetSheet.grossMargin ? (currentBudgetSheet.financialCost * currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2"></td>
          </tr>
          
          <tr>
            <td>销售/售前/动画提成：</td>
            <td>{{ currentBudgetSheet.salesCommission ? currentBudgetSheet.salesCommission.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.salesCommission && currentBudgetSheet.grossMargin ? (currentBudgetSheet.salesCommission *  currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3"></td>
            <td colspan="2"></td>
          </tr>
          
          <tr class="total-row">
            <td>合计：</td>
            <td>{{ currentBudgetSheet.total ? currentBudgetSheet.total.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.total && currentBudgetSheet.grossMargin ? (currentBudgetSheet.total *  currentBudgetSheet.grossMargin).toFixed(2) : '0.00' }}</td>
            <td colspan="3">{{ currentBudgetSheet.total ? currentBudgetSheet.total.toFixed(4) : '0.0000' }}</td>
            <td colspan="2"></td>
          </tr>
          
          <tr class="yellow-bg">
            <td rowspan="12">财务成本</td>
            <td rowspan="3">发货前付款无财务费用</td>
            <td rowspan="3">{{ currentBudgetSheet.proportionReceivedPayment ? currentBudgetSheet.proportionReceivedPayment.toFixed(2) : '0.00' }}</td>
            <td colspan="3">到货款金额</td>
            <td colspan="2"></td>
          </tr>
          
          <tr class="yellow-bg">
            <td>付款周期（天）</td>
            <td>到货款金额比例</td>
            <td>成本小计</td>
            <td colspan="2"></td>
          </tr>
          
          <tr class="yellow-bg">
            <td>{{ currentBudgetSheet.paymentCycle ? currentBudgetSheet.paymentCycle.toFixed(2) : '0' }}</td>
            <td>{{ currentBudgetSheet.proportionReceivedPaymentAmount ? currentBudgetSheet.proportionReceivedPaymentAmount.toFixed(2) : '0' }}</td>
            <td>{{ currentBudgetSheet.proportionReceivedPayment ? currentBudgetSheet.proportionReceivedPayment.toFixed(2) : '0.00' }}</td>
            <td colspan="2"></td>
          </tr>
          
          <tr class="yellow-bg">
            <td rowspan="3">发货至安装验收后</td>
            <td rowspan="3">{{ currentBudgetSheet.installationAcceptancePayment ? currentBudgetSheet.installationAcceptancePayment.toFixed(2) : '0.00' }}</td>
            <td colspan="3">安装验收款金额</td>
            <td colspan="2"></td>
          </tr>
          
          <tr class="yellow-bg">
            <td>付款周期（天）</td>
            <td>安装验收款比例（%）</td>
            <td>成本小计（元）</td>
            <td colspan="2"></td>
          </tr>
          <tr class="yellow-bg">
            <td>{{ currentBudgetSheet.paymentCycle2 ? currentBudgetSheet.paymentCycle2.toFixed(0) : '0' }}</td>
            <td>{{ currentBudgetSheet.installationAcceptancePaymentRatio ? currentBudgetSheet.installationAcceptancePaymentRatio.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.installationAcceptancePayment ? currentBudgetSheet.installationAcceptancePayment.toFixed(2) : '0.00' }}</td>
            <td colspan="2"></td>
          </tr>

          <tr class="yellow-bg">
            <td rowspan="3">验收后质保期限</td>
            <td rowspan="3">{{ currentBudgetSheet.warrantyCost ? currentBudgetSheet.warrantyCost.toFixed(2) : '0.00' }}</td>
            <td colspan="3">质保金</td>
            <td colspan="2"></td>
          </tr>
          
          <tr class="yellow-bg">
            <td>质保期（天）</td>
            <td>质保金比例（%）</td>
            <td>成本小计（元）</td>
            <td colspan="2"></td>
          </tr>
          <tr class="yellow-bg">
            <td>{{ currentBudgetSheet.warrantyPeriodMonth ? currentBudgetSheet.warrantyPeriodMonth.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.warrantyMoney ? currentBudgetSheet.warrantyMoney.toFixed(2) : '0.00' }}</td>
            <td>{{ currentBudgetSheet.warrantyCost ? currentBudgetSheet.warrantyCost.toFixed(2) : '0.00' }}</td>
            <td colspan="2"></td>
          </tr>

          <tr class="yellow-bg">
            <td rowspan="3">常规银行承兑（黑名单另计）</td>
            <td rowspan="3">{{ currentBudgetSheet.acceptanceMoneyCost ? currentBudgetSheet.acceptanceMoneyCost.toFixed(2) : '0.00' }}</td>
            <td colspan="3">承兑费用</td>
            <td colspan="2"></td>
          </tr>
          
          <tr class="yellow-bg">
            <td>承兑时间（月）</td>
            <td>承兑金额（元）</td>
            <td>成本小计（元）</td>
            <td colspan="2"></td>
          </tr>
          <tr class="yellow-bg">
            <td>{{ currentBudgetSheet.acceptanceTime ?? '0' }}</td>
            <td>{{ (currentBudgetSheet.acceptanceMoney !== undefined && currentBudgetSheet.acceptanceMoney !== null) ? String(currentBudgetSheet.acceptanceMoney) : '0.00' }}</td>
            <td>{{ (currentBudgetSheet.acceptanceMoneyCost !== undefined && currentBudgetSheet.acceptanceMoneyCost !== null) ? String(currentBudgetSheet.acceptanceMoneyCost) : '0.00' }}</td>
            <td colspan="2"></td>
          </tr>
          
         
          
          <tr>
            <td colspan="2">销售利润比例：</td>
            <td colspan="2">{{ currentBudgetSheet.grossMargin ? currentBudgetSheet.grossMargin.toFixed(2) : '0.00' }}</td>
            <td rowspan="4">审核</td>
            <td rowspan="4">测试</td>
            <td rowspan="4">审核</td>
            <td rowspan="4">测试</td>
          </tr>
          
          <tr>
            <td>销售提成金额（元）：</td>
            <td colspan="1">{{ currentBudgetSheet.salesCommissionAmount ? currentBudgetSheet.salesCommissionAmount.toFixed(2) : '0.00' }}</td>
            <td>提成标准：</td>
            <td colspan="1">{{ currentBudgetSheet.salesCommissionAmountRatio ? currentBudgetSheet.salesCommissionAmountRatio.toFixed(2) : '0.00' }}</td>
          </tr>
          
          <tr>
            <td>售前规划提成（元）:</td>
            <td colspan="1">{{ currentBudgetSheet.preSalesPlanningCommission ? currentBudgetSheet.preSalesPlanningCommission.toFixed(2) : '0.00' }}</td>
            <td>提成标准：</td>
            <td colspan="1">{{ currentBudgetSheet.preSalesPlanningCommissionRatio ? currentBudgetSheet.preSalesPlanningCommissionRatio.toFixed(2) : '0.00' }}</td>
          </tr>

          <tr>
            <td>项目动画提成（元）：</td>
            <td colspan="1">{{ currentBudgetSheet.projectAnimationCommission ? currentBudgetSheet.projectAnimationCommission.toFixed(2) : '0.00' }}</td>
            <td>提成标准：</td>
            <td colspan="1">{{ currentBudgetSheet.projectAnimationCommissionRatio ? currentBudgetSheet.projectAnimationCommissionRatio.toFixed(2) : '0.00' }}</td>
          </tr>
  
        </table>
        
        <div class="budget-footer">
          <div class="print-area">
            <el-button type="primary" @click="printBudgetSheet" class="print-button">打印预算单</el-button>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="handleCloseBudgetDialog">取消</el-button>
        <el-button type="primary" @click="printBudgetSheet">打印</el-button>
        <el-button type="success" @click="saveBudgetSheet">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBudgetSheetListApi, deleteBudgetSheetApi, getBudgetSheetDetailAllApi, saveHistoricalBudgetSheetApi } from '@/api/budgetSheet/index'
import type { BudgetSheet, BudgetSheetQuery } from '@/api/budgetSheet/type'
import { Search, Refresh, Plus, Document } from '@element-plus/icons-vue'
import ArchiveSelector from "@/components/common/ArchiveSelector.vue"
import { getSimpleProject } from '@/api/project'
import { ProjectDocument, ProjectDocumentListParam } from '@/api/project/type'
import { getSimpleCustomer } from '@/api/companyCustomer'
import { getSimpleUser } from '@/api/user'
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'

// @ts-nocheck

// 遮罩层
const loading = ref(true)
// 总条数
const total = ref(0)
// 预算单表格数据
const dataList = ref<BudgetSheet[]>([])
// 表格高度自适应
const tableHeight = ref(0)

// 项目选项
const projectOptions = ref<any[]>([])
// 客户选项
const customerOptions = ref<any[]>([])
// 业务员选项
const personOptions = ref<any[]>([])

// 查询参数
const queryParams = reactive<BudgetSheetQuery>({
  page: 1,
  limit: 10,
  projectId: undefined,
  customerId: undefined,
  personId: undefined
})

// 项目选择器相关
const projectSelectorVisible = ref(false)
const projectSearchFields = [
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '项目名称', prop: 'name', type: 'input' as const }
]
const projectTableColumns = [
  { label: '项目编号', prop: 'code' },
  { label: '项目名称', prop: 'name' },
  { label: '项目状态', prop: 'status' }
]

// 打印预算单相关
const budgetDialog = reactive({
  visible: false,
  title: '',
  width: '900px'
})

// 当前选中的预算单数据
const currentBudgetSheet = ref<BudgetSheet & {
  integratedPlanningType?: string;
  productCostExpenses?: number;
  productSalesAmount?: number;
  productPackagingExpenses?: number;
  productTransportExpenses?: number;
  shelfInstallationExpenses?: number;
  equipmentInstallationExpenses?: number;
  electricControlInstallationExpenses?: number;
  electricControlDebugExpenses?: number;
  softwareDebugExpenses?: number;
  projectManagementExpenses?: number;
  operationManagementExpenses?: number;
  warrantyPeriod?: number;
  otherExpenses?: number;
  marketingExpenses?: string;
  financialCost?: number;
  salesCommission?: number;
  total?: number;
  marketingExpensesPrice?: number;
  proportionReceivedPayment?: number;
  paymentCycle?: number;
  proportionReceivedPaymentAmount?: number;
  installationAcceptancePayment?: number;
  paymentCycle2?: number;
  installationAcceptancePaymentRatio?: number;
  warrantyCost?: number;
  warrantyPeriodMonth?: number;
  warrantyMoney?: number;
  acceptanceTime?: number | string;
  acceptanceMoney?: number | string;
  acceptanceMoneyCost?: number;
  salesCommissionAmount?: number;
  salesCommissionAmountRatio?: number;
  preSalesPlanningCommission?: number;
  preSalesPlanningCommissionRatio?: number;
  projectAnimationCommission?: number;
  projectAnimationCommissionRatio?: number;
}>({})

// 路由实例
const router = useRouter()

// 使用dialog钩子获取弹窗控制方法
const { dialog, onShow, onClose } = useDialog()

// 获取项目列表 (为ArchiveSelector组件提供)
const fetchProjectList = () => {
  return getSimpleProject()
}

// 处理项目选择
const handleProjectSelect = (selection: ProjectDocument[]) => {
  if (selection && selection.length > 0) {
    queryParams.projectId = selection[0].id
  }
}

// 获取项目选项
const getProjectOptions = async () => {
  try {
    const res = await getSimpleProject()
    projectOptions.value = res.data|| []
  } catch (error) {
    console.error('获取项目列表失败', error)
  }
}

// 获取客户选项
const getCustomerOptions = async () => {
  try {
    const res = await getSimpleCustomer()
    customerOptions.value = res.data || []
  } catch (error) {
    console.error('获取客户列表失败', error)
  }
}

// 获取业务员选项
const getPersonOptions = async () => {
  try {
    const res = await getSimpleUser()
    personOptions.value = res.data || []
  } catch (error) {
    console.error('获取业务员列表失败', error)
  }
}

// 查询预算单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getBudgetSheetListApi(queryParams)
    dataList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取预算单列表失败', error)
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.projectId = undefined
  queryParams.customerId = undefined
  queryParams.personId = undefined
  queryParams.page = 1
  getList()
}

// 新增按钮操作
const handleAdd = () => {
  router.push({ path: '/compute/budgetSheet/form' })
}

// 查看按钮操作
const handleDetail = (id: number) => {
  router.push({ 
    path: `/compute/budgetSheet/form/${id}`,
    query: { display: 'true' }
  })
}

// 编辑按钮操作
const handleEdit = (id: number) => {
  router.push({ path: `/compute/budgetSheet/form/${id}` })
}

// 删除按钮操作
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确认删除该预算单数据吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteBudgetSheetApi(id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除预算单失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  queryParams.limit = size
  getList()
}

// 页码改变
const handleCurrentChange = (page: number) => {
  queryParams.page = page
  getList()
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 格式化金额
const formatPrice = (price: number | undefined) => {
  return price ? `¥ ${price.toFixed(2)}` : '¥ 0.00'
}

// 格式化百分比
const formatPercent = (percent: number | undefined) => {
  return percent ? `${percent.toFixed(2)}%` : '0.00%'
}

// 处理打印按钮点击
const handlePrint = (row: BudgetSheet) => {
  if (!row.id) {
    ElMessage.error('预算单ID不存在，无法打印')
    return
  }
  
  getBudgetSheetDetailAllApi(row.id).then(res => {
    // @ts-ignore - 后端返回的数据结构可能与TypeScript定义不完全一致
    currentBudgetSheet.value = res.data
  })
  budgetDialog.visible = true
  budgetDialog.title = '预算单详情'
}

// 打印预算单
const printBudgetSheet = () => {
  const printWindow = window.open('', 'PRINT', 'height=800,width=1200')
  if (printWindow) {
    const printContents = document.getElementById('budgetContent')?.innerHTML
    
    // 直接使用打印内容
    printWindow.document.write(`
      <html>
        <head>
          <title></title>
          <base href="${window.location.origin}${window.location.pathname}">
          <style>
            body { font-family: SimSun, serif; margin: 0; padding: 0; text-align: center; }
            table { width: 99%; border-collapse: collapse; margin: 0 auto; }
            table, th, td { border: 1px solid black; }
            th, td { padding: 5px; text-align: center; vertical-align: middle; }
            .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; text-align: center; }
            .title { font-size: 18px; font-weight: bold; text-align: center; }
            .date { text-align: center; }
            .yellow-bg { background-color: #FFFF00; }
            .yellow-bg td { text-align: center; vertical-align: middle; }
            .pink-bg { background-color: #FFCCCC; }
            .blue-bg { background-color: #CCFFFF; }
            .total-row { font-weight: bold; }
            .print-button { display: none !important; }
            .budget-header { 
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 24px;
              padding-bottom: 16px;
              border-bottom: 1px solid #ebeef5;
              position: relative;
              text-align: center;
            }
            .budget-logo {
              position: absolute;
              top: 10px;
              text-align: center;
            }
            .budget-logo img.logo-image {
              max-width: 150px;
              height: auto;
              margin: 0 auto;
            }
            .budget-info {
              text-align: center;
              margin: 0 auto;
              width: 100%;
            }
            .budget-info h2 {
              margin: 0;
              font-size: 24px;
              color: #303133;
              text-align: center;
            }
            .budget-date {
              text-align: center;
              font-size: 14px;
              color: #606266;
            }
            .budget-table {
              width: 99%;
              border-collapse: collapse;
              margin: 16px auto;
            }
            .budget-table td {
              text-align: center;
              vertical-align: middle;
              padding: 8px;
              border: 1px solid #000;
            }
            .budget-footer {
              margin-top: 24px;
              padding-top: 16px;
              border-top: 1px solid #ebeef5;
              display: flex;
              justify-content: center;
              align-items: center;
              text-align: center;
            }
            .total-row td {
              font-weight: bold;
              background-color: #f2f2f2;
              text-align: center;
              vertical-align: middle;
            }
          </style>
        </head>
        <body>
          ${printContents}
        </body>
      </html>
    `)
    printWindow.document.close()
    printWindow.focus()
    printWindow.print()
    printWindow.close()
    budgetDialog.visible = false
  } else {
    ElMessage.error('无法打开打印窗口，请检查浏览器设置')
  }
}

// 关闭预算单弹窗
const handleCloseBudgetDialog = () => {
  budgetDialog.visible = false
}

// 保存预算单到历史记录
const saveBudgetSheet = () => {
  if (!currentBudgetSheet.value || !currentBudgetSheet.value.id) {
    ElMessage.warning('未获取到预算单数据，无法保存')
    return
  }
  
  // 获取打印内容的HTML和CSS样式
  const contentElement = document.getElementById('budgetContent')
  if (!contentElement) {
    ElMessage.error('获取预算单内容失败')
    return
  }
  
  // 构建完整的HTML内容，包含样式
  const styleContent = `
    <style>
      body { font-family: SimSun, serif; margin: 0; padding: 0; text-align: center; }
      table { width: 99%; border-collapse: collapse; margin: 0 auto; }
      table, th, td { border: 1px solid black; }
      th, td { padding: 5px; text-align: center; vertical-align: middle; }
      .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; text-align: center; }
      .title { font-size: 18px; font-weight: bold; text-align: center; }
      .date { text-align: center; }
      .yellow-bg { background-color: #FFFF00; }
      .yellow-bg td { text-align: center; vertical-align: middle; }
      .pink-bg { background-color: #FFCCCC; }
      .blue-bg { background-color: #CCFFFF; }
      .total-row { font-weight: bold; }
      .print-button { display: none !important; }
      .budget-header { 
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #ebeef5;
        position: relative;
        text-align: center;
      }
      .budget-logo {
        position: absolute;
        top: 10px;
        text-align: center;
      }
      .budget-logo img.logo-image {
        max-width: 150px;
        height: auto;
        margin: 0 auto;
      }
      .budget-info {
        text-align: center;
        margin: 0 auto;
        width: 100%;
      }
      .budget-info h2 {
        margin: 0;
        font-size: 24px;
        color: #303133;
        text-align: center;
      }
      .budget-date {
        text-align: center;
        font-size: 14px;
        color: #606266;
      }
      .budget-table {
        width: 99%;
        border-collapse: collapse;
        margin: 16px auto;
      }
      .budget-table td {
        text-align: center;
        vertical-align: middle;
        padding: 8px;
        border: 1px solid #000;
      }
      .budget-footer {
        margin-top: 24px;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
      }
      .total-row td {
        font-weight: bold;
        background-color: #f2f2f2;
        text-align: center;
        vertical-align: middle;
      }
    </style>
  `
  
  // 获取内容并移除打印按钮
  let htmlContent = contentElement.innerHTML
  // 将打印按钮部分替换为空
  htmlContent = htmlContent.replace(/<div class="budget-footer">[\s\S]*?<\/div>/g, '')
  
  // 完整的HTML文档
  const fullContent = `
    <div class="budget-content">
      ${htmlContent}
    </div>
    ${styleContent}
  `
  
  // 构建保存数据
  const saveData = {
    budgetSheetId: currentBudgetSheet.value.id,
    projectId: currentBudgetSheet.value.projectId || 0,
    content: fullContent
  }
  
  // 调用保存API
  saveHistoricalBudgetSheetApi(saveData)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success('预算单保存成功')
        handleCloseBudgetDialog()
      } else {
        ElMessage.error(res.msg || '保存预算单失败')
      }
    })
    .catch((err) => {
      console.error('保存预算单失败', err)
      ElMessage.error('保存预算单失败')
    })
}

onMounted(() => {
  getProjectOptions()
  getCustomerOptions()
  getPersonOptions()
  getList()
  
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    nextTick(() => {
      tableHeight.value = window.innerHeight - 260
    })
  })
})
</script>

<style scoped lang="scss">
.container {
  padding: 20px 20px 0px;

  /*顶部搜索卡片*/
  .search-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 15px 20px;
    }

    /*搜索表单*/
    .search-wrapper {
      .demo-form-inline {
        .el-form-item {
          margin-bottom: 0;
          margin-right: 15px;

          &:last-child {
            margin-right: 0;
          }

          .separator {
            margin: 0 5px;
            color: #909399;
          }
        }

        .el-input,
        .el-select {
          width: 220px;
        }
      }
    }
  }

  /*数据表格卡片*/
  .list-card {
    :deep(.el-card__body) {
      padding: 15px 20px 5px;
    }

    /*表格样式*/
    :deep(.el-table) {
      // 表格内容样式
      .price-value {
        font-weight: 600;
        color: #f56c6c;
      }

      .date-value {
        color: #606266;
      }
    }
  }

  // 分页器
  .pagination {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
  }

  /* 打印预算单弹窗 */
  .print-content {
    padding: 20px;
  }
}

.budget-content {
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;

  .budget-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;

    .budget-logo {
      position: absolute;
      top: 10px;
      text-align: center;

      .logo-image {
        max-width: 150px;
        height: auto;
        margin: 0 auto;
      }
    }

    .budget-info {
      text-align: center;
      margin: 0 auto;
      width: 100%;

      h2 {
        margin: 0;
        font-size: 24px;
        color: #303133;
        text-align: center;
      }
    }

    .budget-date {
      text-align: center;
      font-size: 14px;
      color: #606266;
    }
  }

  .budget-table {
    width: 99%;
    border-collapse: collapse;
    margin: 16px auto;
    
    td {
      padding: 8px;
      border: 1px solid #000;
      text-align: center;
      vertical-align: middle;
    }
    
    .yellow-bg {
      background-color: #FFFF00;
      
      td {
        text-align: center;
        vertical-align: middle;
        font-weight: normal;
      }
    }
    
    .pink-bg {
      background-color: #FFCCCC;
    }
    
    .blue-bg {
      background-color: #CCFFFF;
    }
  }

  .budget-footer {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
  }
}

@media print {
  body {
    width: 100%;
    margin: 0;
    padding: 0;
  }

  .budget-content {
    padding: 0;
    box-shadow: none;
  }

  .budget-table {
    font-size: 12px;
    
    td {
      padding: 5px;
    }
  }

  .budget-footer {
    display: none !important;
  }
  
  .print-button {
    display: none !important;
  }
}
</style> 